package info.androidhive.slidingmenu;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Calculation extends ActionBarActivity implements ActionBar.TabListener {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
	 * derivative, which will keep every loaded fragment in memory. If this
	 * becomes too memory intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;

	public static String prodNameDP;
	public static String layer;
	public static String layerItem;
	static String[] btn;
	private static int clickedPosition = -1;
	private static CheckBox currentCheckBox;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_detail);

		getActionBar().setIcon(R.drawable.ic_calculator);
		
		Intent myIntent = getIntent();
		prodNameDP = myIntent.getStringExtra("prodName");
		layerItem = myIntent.getStringExtra("layerItem");
		btn = layerItem.split(",");
		layer = btn[0];
		
		// Set up the action bar.
		final ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		actionBar.setTitle(prodNameDP);
		actionBar.setDisplayHomeAsUpEnabled(true);

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the activity.
		mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		// When swiping between different sections, select the corresponding
		// tab. We can also use ActionBar.Tab#select() to do this if we have
		// a reference to the Tab.
		mViewPager
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						actionBar.setSelectedNavigationItem(position);
						
					}
				});

		// For each of the sections in the app, add a tab to the action bar.
		for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
			// Create a tab with text corresponding to the page title defined by
			// the adapter. Also specify this Activity object, which implements
			// the TabListener interface, as the callback (listener) for when
			// this tab is selected.
			actionBar.addTab(actionBar.newTab()
					.setText(mSectionsPagerAdapter.getPageTitle(i))
					.setTabListener(this));
		}	
	}
	
	class memberTask extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			JSONObject json = JSONfunctions.getJSONfromURL("http://dongpang.co.kr/android/admin.v02/calculationMember.php");

			try {
				JSONArray dongpang = json.getJSONArray("dongpang");
				JSONObject jobject = dongpang.getJSONObject(0);
				layerItem = jobject.getString("admin_id");
			} catch (JSONException e) {
				Log.e("log_tag", "Error Parsing data" + e.toString());
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
		
			super.onPostExecute(result);
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.

		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			break;

		default:
			return super.onOptionsItemSelected(item);
		}
		return true;

	}

	@Override
	public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			// getItem is called to instantiate the fragment for the given page.
			// Return a CalculationFragment (defined as a static inner class
			// below).
			
			return CalculationFragment.newInstance(position);
		}

		@Override
		public int getCount() {
			return btn.length;
		}

		@Override
		public CharSequence getPageTitle(int position) {

			Locale l = Locale.getDefault();
			return btn[position].toUpperCase(l);

		}
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class CalculationFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		private static final String ARG_SECTION_NUMBER = "section_number";

		/**
		 * Returns a new instance of this fragment for the given section number.
		 */
		public static CalculationFragment newInstance(int sectionNumber) {
			
			CalculationFragment fragment = new CalculationFragment();
			Bundle args = new Bundle();
			args.putInt(ARG_SECTION_NUMBER, sectionNumber);
			fragment.setArguments(args);
			return fragment;
		}

		public CalculationFragment() {}

		
		DecimalFormat df = new DecimalFormat("###,###");

		// list
		static class Data {
			String rowid;
			String prodName;
			String id;
			String price;
			String check;
			boolean check2;
			String admin;
		}

		static class ViewHolder {
			RelativeLayout data;
			RelativeLayout total;
			
			CheckBox checkBox1;
			TextView name;
			TextView amt;
			TextView price;
			TextView admin;
			
			TextView sMoney;
			TextView mMoney;
			TextView eMoney;
		}

		ArrayList<Data> datasList = new ArrayList<Data>();	

		ListView list;
		ListAdapter listAdapter;
		
        private final int GET_CODE = 0;
        private TextView mResults;
        String adminId;
		
		class ListAsynicTask extends AsyncTask<Object, Object, Object> {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}

			@Override
			protected Object doInBackground(Object... params) {
				// TODO Auto-generated method stub

				
				if(btn[getArguments().getInt(ARG_SECTION_NUMBER)].equals("all")){
					adminId = "";
				}else{
					adminId = btn[getArguments().getInt(ARG_SECTION_NUMBER)];
				}
				JSONObject json = JSONfunctions.getJSONfromURL("http://www.dongpang.co.kr/android/admin.v02/calculation_list.php?admin=" + adminId);

				try {
					JSONArray earthquakes = json.getJSONArray("dongpang");

					for (int i = 0; i < earthquakes.length(); i++) {
						JSONObject jobject = earthquakes.getJSONObject(i);

						Data data = new Data();
						
						data.rowid = jobject.getString("rowid");
						data.prodName = jobject.getString("prodName");
						data.id = jobject.getString("id");
						data.price = jobject.getString("price");
						data.check = jobject.getString("check");
						data.admin = jobject.getString("admin");
						
						datasList.add(data);

					}
				} catch (JSONException e) {
					Log.e("log_tag", "Error Parsing data" + e.toString());
				}				
				
				
				return null;
			}

			@Override
			protected void onPostExecute(Object result) {
				listAdapter.notifyDataSetChanged();
				super.onPostExecute(result);
			}

		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.failure, container, false);
			list = (ListView) rootView.findViewById(R.id.list);

			listAdapter = new ListAdapter(getActivity(),R.layout.calculation_row_1, datasList);
			list.setAdapter(listAdapter);
			
			if (datasList == null || datasList.size() == 0) {
				new ListAsynicTask().execute(null, null, null);
			}
			Log.d("","ListAsynicTask");
			
			return rootView;
		}
		

		
		class ListAdapter extends ArrayAdapter<Data> {


			public ListAdapter(Context context, int resource, ArrayList<Data> items) {
				super(context, resource, items);
			}

			@Override
			public View getView(final int position, View convertView, ViewGroup parent) {

				if (convertView == null) {
					convertView = getActivity().getLayoutInflater().inflate(R.layout.calculation_row_1, null);
				}

				ViewHolder viewHolder;
				
				
				
				if (convertView.getTag() == null) {
					
					viewHolder = new ViewHolder();
								
					viewHolder.checkBox1 = (CheckBox) convertView.findViewById(R.id.checkBox1);
					viewHolder.name = (TextView) convertView.findViewById(R.id.name);
					viewHolder.amt = (TextView) convertView.findViewById(R.id.amt);
					viewHolder.price = (TextView) convertView.findViewById(R.id.price);
					viewHolder.admin = (TextView) convertView.findViewById(R.id.adminmemo);
					
					viewHolder.sMoney = (TextView) convertView.findViewById(R.id.sMoney);
					viewHolder.mMoney = (TextView) convertView.findViewById(R.id.mMoney);
					viewHolder.eMoney = (TextView) convertView.findViewById(R.id.eMoney);
					
					viewHolder.data = (RelativeLayout) convertView.findViewById(R.id.data);
					viewHolder.total = (RelativeLayout) convertView.findViewById(R.id.total);
					
					convertView.setTag(viewHolder);
				} else {
					viewHolder = (ViewHolder) convertView.getTag();
				}

				viewHolder.data.setVisibility(View.GONE);
				viewHolder.total.setVisibility(View.GONE);

				if("total".equals(getItem(position).rowid)){
					viewHolder.total.setVisibility(View.VISIBLE);
					viewHolder.sMoney.setText(df.format(Double.parseDouble(getItem(position).prodName)));
					viewHolder.mMoney.setText(df.format(Double.parseDouble(getItem(position).id)));
					viewHolder.eMoney.setText(df.format(Double.parseDouble(getItem(position).price)));
				}else{
					viewHolder.data.setVisibility(View.VISIBLE);
					viewHolder.name.setText(getItem(position).prodName);
					viewHolder.amt.setText(getItem(position).rowid);
					viewHolder.admin.setText(getItem(position).id);
					viewHolder.price.setText(df.format(Double.parseDouble(getItem(position).price)));
					viewHolder.checkBox1.setFocusable(false);
					viewHolder.checkBox1.setClickable(false);
					if((getItem(position).check).equals("Y")){
						viewHolder.checkBox1.setChecked(true);
					}else{
						viewHolder.checkBox1.setChecked(false);
					}
				}		
				convertView.setOnClickListener(new MyListener(viewHolder.checkBox1, position));

				return convertView;
			}
			
			class MyListener implements View.OnClickListener{
				CheckBox checkBox;
				int position;
				public MyListener(CheckBox checkBox, int position) {
					this.checkBox = checkBox;
					this.position = position;
				}
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(getActivity(), CalculationDetail.class);
					intent.putExtra("memberid", getItem(position).id);
					intent.putExtra("shopname", getItem(position).prodName);
					intent.putExtra("check", getItem(position).check);
					intent.putExtra("position", position);
					intent.putExtra("adminId", adminId);
					clickedPosition = position;
					currentCheckBox = checkBox;
	                startActivityForResult(intent, GET_CODE);
				}
				
			}
		}
		
		
		
		
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
        	if(requestCode == GET_CODE && resultCode == RESULT_OK){
        		boolean result = data.getBooleanExtra("checked", true);
        		Log.d("","result:"+result);
        		currentCheckBox.setChecked(result);
        		if(result == true){
        			listAdapter.getItem(clickedPosition).check = "Y";
        		}else{
        			listAdapter.getItem(clickedPosition).check = "";
        		}
        	}
        }
        

	}
	
}